<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="off" label-position="left">
      <!-- 放置标题图片 @是设置的别名-->
      <div class="title-container">
        <h3 class="title">
          <img src="@/assets/common/login-logo.png" alt="" />
        </h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名" name="username" type="text" tabindex="1" auto-complete="off" />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="请输入密码"
          name="password"
          tabindex="2"
          auto-complete="off"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>

      <el-button class="loginBtn" :loading="loading" type="primary" style="width: 100%; margin-bottom: 30px" @click="handleLogin">登录</el-button>
    </el-form>
  </div>
</template>

<script>
import { mapState } from 'vuex'
// 导入公共的工具函数
import { validUsername } from '@/utils/validate'
// import { mapActions } from 'vuex'
// 自定义的用户名校验函数
const validateUsername = (rule, value, callback) => {
  if (!validUsername(value)) {
    return callback(new Error('用户名必须是合法的手机号码'))
  }
  callback()
}
export default {
  name: 'Login',
  data() {
    return {
      // 定义表单数据
      loginForm: {
        username: '13800000002', // 13800000002
        // password: '888itcast.CN764%...' // 888itcast.CN764%...
        password: '123456' // 888itcast.CN764%...
      },
      // 表单校验
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: '用户名不能为空' }, // 内置的校验规则
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, trigger: 'blur', message: '密码不能为空' },
          { min: 6, trigger: 'blur', message: '密码长度不能小于6位' }
        ]
      },
      loading: false,
      passwordType: 'password', // 控制密码的显示和隐藏
      redirect: undefined // 待跳转的完整路由地址
    }
  },
  computed: {
    ...mapState('permission', ['routes'])
  },
  watch: {
    // 深度侦听$route的变化
    $route: {
      handler: function (route) {
        // 如果不是从首页退回来，再次登录时要跳到上次退出时的页面
        this.redirect = route.query && route.query.redirect
        // 如果当前回退的路由地址，不在下一个登录用户的路由权限中，让他直接登录成功后跳到首页
        // 因为地址默认encodeURIComponent转码了，所以在判断是需要先转码
        const path = decodeURIComponent(this.redirect)
        this.routes.forEach(item => {
          // 判断当前用户是否有回退地址这个路由对象的权限
          if (item.path !== path) {
            // 没有就不应该跳回去，跳回去会报404错误，应该让其跳首页
            this.redirect = '/'
          }
        })
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // ...mapActions('user', ['login']),
    // 进行显示和隐藏的切换
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = 'text'
      } else {
        this.passwordType = 'password'
      }
      // 让密码输入框获取焦点
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    // 实现登录功能
    handleLogin() {
      // 验证
      this.$refs.loginForm.validate(async valid => {
        if (!valid) return false // 如果验证不通过，必须返回false
        // 验证通过,调用vuex中存储token的actions方法
        // await this.login({ ...this.loginForm, mobile: this.loginForm.username })
        this.loading = true // 按钮转圈
        try {
          await this.$store.dispatch('user/login', { ...this.loginForm, mobile: this.loginForm.username })
          // 提示信息
          this.$message.success('登录成功')
          // 跳转到指定的路由地址上去
          this.$router.push(this.redirect || '/')
        } catch (err) {
          console.log(err)
        } finally {
          // 不管成功或者失败都会走这里
          this.loading = false // 按钮不转圈
        }
      })
    }
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #68b0fe;
$cursor: #fff;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background-image: url('~@/assets/common/login.jpg'); // 设置背景图片，引入本地图片时必须前面加~
  background-position: center; // 将图片位置设置为充满整个屏幕
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $light_gray;
      height: 47px;
      caret-color: $cursor;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background: rgba(255, 255, 255, 0.7); // 输入登录表单的背景色
    border-radius: 5px;
    color: #454545;
  }
  .loginBtn {
    background: #407ffe;
    height: 64px;
    line-height: 32px;
    font-size: 24px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
